package com.zsc.shixun.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


/**
 * @Classname MailUtils
 * @Description 邮件发送工具类
 * @Date 2019-3-14 16:25
 * @Created by CrazyStone
 */
@Service
public class MailUtils {
    private static final Logger logger = LoggerFactory.getLogger(MailUtils.class);
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Value("${spring.mail.username}")
    private String mailfrom;
    //Thymeleaf提供的模板引擎解析器
    @Autowired
    TemplateEngine templateEngine;

    /**
     * 发送简单邮件
     *
     * @param mailto
     * @param title
     * @param content
     */

    public void sendSimpleEmail(String mailto, String title, String content) {
        //  定制邮件发送内容
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailfrom);
        message.setTo(mailto);
        message.setSubject(title);
        message.setText(content);
        try {
            // 发送邮件
            mailSender.send(message);
            logger.info("发送成功");
        } catch (Exception e) {
            logger.error("简单邮件发送失败");
        }

    }


    /**
     * 发送验证码邮件
     *
     * @param mailto
     * @param title
     * @param code
     */
    public void sendCodeEmail(String mailto, String title, String code) {
        //  定制邮件发送内容
        MimeMessage message = mailSender.createMimeMessage();
        Context context = new Context();
        context.setVariable("code", code);
        String emailContent = templateEngine.process("emailCodeTemplate", context);
        try {
            //在定制Html模板邮件信息时，、使用了MimeMessageHelper类对邮件信息进行封装处理。
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailfrom);
            helper.setTo(mailto);
            helper.setSubject(title);
            helper.setText(emailContent, true);
            mailSender.send(message);
            System.out.println("模板邮件发送成功");
        } catch (MessagingException e) {
            System.out.println("模板邮件发送失败 " + e.getMessage());
            e.printStackTrace();
        }
    }


}

